//
//  SideslipView.swift
//  Exchange
//
//  Created by 孟祥群 on 2018/4/28.
//  Copyright © 2018年 common. All rights reserved.
//

import UIKit
typealias closelip = () ->()
typealias sideslip = (MarketCoinModel) ->()
class SideslipView: UIView, UITableViewDelegate, UITableViewDataSource {
    var coinArr:[String] = []
    var selectArr:[MarketCoinModel]  = []
    
    var currentPairModel:MarketCoinModel = MarketCoinModel()//当前订阅的币种对
    
    var selectName:String = ""
    var loadBool = false
    var sideslipBlock:sideslip?
    var closelipBlock:closelip?
    lazy var tableView: UITableView = {
        let tableView = UITableView(frame: CGRect.zero, style: UITableViewStyle.grouped)
        tableView.separatorStyle = UITableViewCellSeparatorStyle.none
        tableView.delegate = self
        tableView.dataSource = self
        tableView.themeBackground = ThemeManager.ThemeColorKeys.background
        return tableView
    }()
    
    var headView:UIView?
    
    lazy var scrollview:UIScrollView = {
        let scrol = UIScrollView()
        return scrol
    }()
    var sectionArr:NSMutableArray = []
    override init(frame: CGRect) {
        super.init(frame: frame)
        let tap = UITapGestureRecognizer(target: self, action: #selector(giveUpFirstRespond))
        tap .numberOfTouchesRequired = 1;
        tap .numberOfTapsRequired = 1;
        self.addGestureRecognizer(tap)
        
        self.setUpUI()
    }
    
    //开始订阅
    func startSubscription() {
        self.changePairStates(states: true)
    }
    
    //更新选中的币对名称
    func updateHeadInformation()  {
        self.coinArr = APPTransactionPair.default.archiveTitleArray()
        if self.coinArr.count > 0 {
            let code = self.coinArr.first ?? ""
            self.selectArr =   APPTransactionPair.default.archivePairArray(coinName:code)
            selectName = code
            self.loadBool = true
        }
        self.tableView.reloadData()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setUpUI() -> Void {
        UIApplication.shared.keyWindow?.addSubview(self)
        self.frame = CGRect(x: 0, y: 0, width: kSCREEN_WIDTH, height: kSCREEN_HEIGHT)
        self.backgroundColor = UIColor.black.withAlphaComponent(0.2)
        self.snp.makeConstraints { (make) in
            make.top.bottom.left.right.equalToSuperview()
        }
        
        let tap = UITapGestureRecognizer(target: self, action: #selector(giveUpFirstRespond(sender:)))
        tap.numberOfTapsRequired = 1
        tap.cancelsTouchesInView = false
        self.addGestureRecognizer(tap)
        
        self.addSubview(tableView)
//        tableView.frame = CGRect(x: 0, y: 0, width: kSCREEN_WIDTH*0.7, height: kSCREEN_HEIGHT)
        tableView.themeBackground = ThemeManager.ThemeColorKeys.background
        tableView.snp.makeConstraints { (make) in
            make.top.bottom.equalToSuperview()
            make.width.equalTo(kSCREEN_WIDTH*0.7)
            make.left.equalToSuperview()
        }
        
        self.updateHeadInformation()
        
    }
    
    //MARK: tableViewDelegate
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.selectArr.count
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let identy = "identy"
        var cell = tableView.dequeueReusableCell(withIdentifier: identy) as? DiskDataTableViewCell
        if cell == nil {
            cell = DiskDataTableViewCell(style: .default, reuseIdentifier: identy)
            
            cell?.diskLabel.snp.remakeConstraints { (make) in
                make.left.equalToSuperview().offset(15)
                make.centerY.equalToSuperview()
                make.width.lessThanOrEqualTo(kSCREEN_WIDTH*0.7/3 - 2)
            }
            cell?.priceLabel.textColor = kGreenColor
            cell?.priceLabel.textAlignment = NSTextAlignment.center
            cell?.priceLabel.snp.remakeConstraints { (make) in
                make.centerX.equalToSuperview()
                make.width.equalTo(kSCREEN_WIDTH*0.7/3 - 5)
                make.centerY.equalToSuperview()
            }
            cell?.numberLabel.textAlignment = NSTextAlignment.right
            cell?.numberLabel.snp.remakeConstraints { (make) in
                make.right.equalToSuperview().offset(isiphone5S() ? -10 : -15)
                make.width.equalTo(kSCREEN_WIDTH*0.7/3-(isiphone5S() ? -15 : -10))
                make.centerY.equalToSuperview()
            }
            
            let line = UIView()
            line.themeBackground = ThemeManager.ThemeColorKeys.tabLineColor
            cell?.contentView.addSubview(line)
            line.snp.makeConstraints { (make) in
                make.left.equalToSuperview().offset(15)
                make.right.equalToSuperview().offset(-15)
                make.height.equalTo(0.5)
                make.bottom.equalToSuperview()
            }
            
            cell?.diskLabel.themeTextColor = ThemeManager.ThemeColorKeys.text1
            if isiphone5S() {
                cell?.priceLabel.font = UIFont.systemFont(ofSize: 13)
                cell?.numberLabel.font = UIFont.systemFont(ofSize: 13)
                cell?.diskLabel.font = UIFont.systemFont(ofSize: 13)
            }else {
                cell?.priceLabel.font = UIFont.systemFont(ofSize: 15)
                cell?.numberLabel.font = UIFont.systemFont(ofSize: 15)
                cell?.diskLabel.font = UIFont.systemFont(ofSize: 15)
            }
            
        }
        let model = self.selectArr[indexPath.row]
        cell?.diskLabel.text = model.name
        cell?.priceLabel.text = CYCalculate.cy_intercept(number: model.price , digit: 8)
        
        if model.price > 0 {
            let open = model.open == 0 ? 1 : model.open
            let increase = (model.price - model.open) * 100 / open
            if increase >= 0 {
                cell?.numberLabel.text = String(format: "+%0.2f%%", increase)
                cell?.numberLabel.textColor = kGreenColor
                cell?.priceLabel.textColor = kGreenColor
            }else {
                cell?.numberLabel.text = String(format: "%0.2f%%", increase)
                cell?.numberLabel.textColor = kRedColor
                cell?.priceLabel.textColor = kRedColor
            }
        }else {
            cell?.priceLabel.textColor = kRedColor
            cell?.numberLabel.text = ""
        }
        return cell!
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        return 48
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 64
    }
    
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
       let model = self.selectArr[indexPath.row]
        if sideslipBlock != nil {
            sideslipBlock!(model)
            self.closeSides()
        }
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
      let view:UIView = UIView(frame: CGRect(x: 0, y: 0, width: Int(kSCREEN_WIDTH*0.7), height: 64))
      if loadBool {
        headView = view
        let backBtn  = UIButton()
        backBtn.addTarget(self, action: #selector(backBtnAction), for: UIControlEvents.touchUpInside)
        backBtn.themeSetImage(ThemeManager.ThemeImageKeys.coinRetractRight, for: UIControlState.normal)
        view.addSubview(backBtn)
        backBtn.snp.makeConstraints { (make) in
            make.bottom.equalToSuperview()
            make.right.equalToSuperview()
            make.height.equalTo(30)
            make.width.equalTo(37)
        }
        view.addSubview(scrollview)
        scrollview.frame = CGRect(x: 15, y: 0, width: kSCREEN_WIDTH*0.7-42, height: 64)
        sectionArr.removeAllObjects()
        for (index,model) in self.coinArr.enumerated() {
            let btn = UIButton()
            btn.setTitle(model , for: UIControlState.normal)
            btn.addTarget(self, action: #selector(selectAction(sender:)), for: UIControlEvents.touchUpInside)
            btn.tag = KBtnTag + index
            btn.setTitleColor(kTextColor, for: UIControlState.normal)
            btn.titleLabel?.font = UIFont.systemFont(ofSize: 11)
            btn.layer.cornerRadius = 11
            btn.layer.masksToBounds = true
            scrollview.addSubview(btn)
            btn.snp.makeConstraints { (make) in
                make.left.equalToSuperview().offset(index*63)
                make.centerY.equalTo(backBtn)
                make.height.equalTo(22)
                make.width.equalTo(60)
            }
            
            sectionArr.add(btn)
        }
        scrollview.contentSize = CGSize(width: sectionArr.count*63, height: 0)
        self.changeStyle(selectIndex: 0)
        loadBool = false
      }
        return headView
    }
    
    @objc func selectAction(sender:UIButton) {
        if sender.titleLabel?.text == selectName {
            return
        }
        
        self.changeStyle(selectIndex: sender.tag - KBtnTag)
        self.selectArr =  APPTransactionPair.default.archivePairArray(coinName:sender.titleLabel?.text ?? "")
        //切换取消上一个的订阅
        APPTransactionPair.default.cancelSubscribe(key:selectName)
        APPTransactionPair.default.subscribe(key:sender.titleLabel?.text ?? "")
        selectName = sender.titleLabel?.text ?? ""
        tableView.reloadData()
    }
    
    
    func changeStyle(selectIndex:Int) -> Void {
        sectionArr.enumerateObjects { (sender, index, stop) in
            let btn = sender as AnyObject as! UIButton
            if index == selectIndex {
                btn.backgroundColor = kThemeColor
                btn.setTitleColor(UIColor.white, for: UIControlState.normal)
            }else {
                btn.backgroundColor = UIColor.clear
                btn.setTitleColor(kTextColor, for: UIControlState.normal)
            }
        }
    }
    
    func showSides() -> Void {
        self.layoutIfNeeded()
        tableView.creatBaseAnimation(fromValue: CGPoint(x: -kSCREEN_WIDTH*0.7, y: tableView.layer.position.y), toValue: CGPoint(x: tableView.layer.position.x, y: tableView.layer.position.y), duration: 0.5, keyName: "position")
    }
    
    func closeSides() -> Void {

        tableView.creatBaseAnimation(fromValue: CGPoint(x: tableView.layer.position.x, y: tableView.layer.position.y), toValue: CGPoint(x: -kSCREEN_WIDTH*0.7, y: tableView.layer.position.y) , duration: 0.5, keyName: "position")
        let time: TimeInterval = 0.3
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + time) {
            self.isHidden = true
        }
        APPTransactionPair.default.cancelSubscribe(key: selectName)
        
        if closelipBlock != nil {
            closelipBlock!()
        }
        
    }
    
    @objc func backBtnAction() {
        self.closeSides()
    }
    
    /// 订阅推送
    ///
    /// - Parameter states: 订阅 or 取消
    func changePairStates(states:Bool)  {
        let symbols = currentPairModel.name
        if symbols.count == 0 {
            return
        }
        let nameArr = symbols.components(separatedBy: "/")
        if nameArr.count < 2 {
            return
        }
        if nameArr.last == nil {
            return
        }
        if states == true {
            APPTransactionPair.default.subscribe(key: nameArr.last!)
        }else {
            APPTransactionPair.default.cancelSubscribe(key: nameArr.last!)
        }
        
    }
    
    @objc func giveUpFirstRespond(sender:UITapGestureRecognizer) -> Void {
        if (sender.state == UIGestureRecognizerState.ended) {
            let location = sender.location(in: self)
            if !tableView.point(inside: tableView.convert(location, from: self), with: nil) {
                self.closeSides()
            }
        }
    }
    
    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */

}
